package tjs.styudy.mini.springboot.transaction.config;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Nicky.Tang on 2021/10/27 4:36 下午
 *
 * @since 02.12.10
 */
public class TransactionInfo {

    private Connection connection;

    // 当前connection是否为事务创建者
    private boolean newTransaction = false;

    public ConnectionHolder createConnectionIfNecessary(DataSource dataSource, boolean needNew) {
        ConnectionHolder curConnectionHolder = null;
        ConnectionHolder lastConnectionHolder = ConnectionHolder.getResource();
        if (lastConnectionHolder == null || needNew) {
            curConnectionHolder = newOneConnectionHolder(dataSource, lastConnectionHolder);
        } else if (!needNew) {
            curConnectionHolder = lastConnectionHolder;
        }
        return curConnectionHolder;
    }

    private ConnectionHolder newOneConnectionHolder(DataSource dataSource, ConnectionHolder lastConnectionHolder) {
        this.newTransaction = true;
        ConnectionHolder connectionHolder = new ConnectionHolder();
        connectionHolder.setLastConnectionHolder(lastConnectionHolder);
        Connection newConnection = null;
        try {
            newConnection = dataSource.getConnection();
            // fixme 关闭自动提交，间接开启事务
            newConnection.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        connectionHolder.setCurConnection(newConnection);
        return connectionHolder;
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public boolean isNewTransaction() {
        return newTransaction;
    }

    public void setNewTransaction(boolean newTransaction) {
        this.newTransaction = newTransaction;
    }
}
